let container = document.querySelector('.container');
const imgWidth = 240;

function getHeight(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function col() {
    let columns = Math.floor(container.clientWidth / imgWidth);
    let spaceNumber = columns + 1;
    let totalSpace = container.clientWidth - columns * imgWidth;
    let space = totalSpace / spaceNumber;
    return {
        columns,
        space
    }
}

function getMin(arr) {
    let min = arr[0];
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] < min) {
            min = arr[i]
        }
    }
    return min;
}

function getMax(arr) {
    let max = arr[0];
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i]
        }
    }
    return max;
}

function setPositions() {
    const info = col();
    let arr = new Array(info.columns);
    arr.fill(0);
    for (let i = 0; i < container.children.length; i++) {
        const img = container.children[i];
        let minTop = getMin(arr);
        img.style.top = minTop + 'px';
        let index = arr.indexOf(minTop);
        arr[index] += img.height + info.space;
        let left = (index + 1) * info.space + index * imgWidth;
        img.style.left = left + 'px';
    }
    let max = getMax(arr);
    container.style.height = max + 'px';
}

function createImg() {
    for (let i = 0; i < 40; i++) {
        let img = document.createElement('img');
        img.src = "./imgs/img.webp";
        img.className = 'img';
        img.style.width = imgWidth + 'px'
        img.style.height = getHeight(150, 350) + 'px';

        container.appendChild(img);

        img.onload = setPositions;
    }


}

let timer = null;
function bindEvnet() {
    window.onresize = function () {
        if (timer) {
            this.clearInterval(timer);

        }
        timer = this.setTimeout(setPositions, 300);
    }
}

function main() {
    createImg();
    bindEvnet();
}

main();